package com.tjhk.lock.cas;

import java.util.concurrent.atomic.AtomicReference;

public class UnfairLock {
    /**
     * 锁获得者
     */
    private AtomicReference<Thread> owner = new AtomicReference<>();

    /**
     * 锁重入次数
     */
    private static volatile int count = 0;

    public void lock(){
        Thread current = Thread.currentThread();
        if (current == owner.get()){
            count++;
            System.out.println(current.getName()+"进入锁,count:"+count);
            return;
        }
        while (!owner.compareAndSet(null,current));
    }

    public void unlock(){
        Thread current = Thread.currentThread();
        if (current == owner.get()){
            System.out.println(current.getName()+"进入锁,count:"+count);
            if (count > 0){
                count --;
            }else {
                owner.set(null);
            }
        }
    }
}
